#include "Arduino.h"
#include "GeLightShow.h"
#include "LightData.h"

GeLightShow::GeLightShow(int dataPin)
{
	_lightCount = 50;
	_dataPin = dataPin;
	pinMode(_dataPin, OUTPUT);
}

GeLightShow::GeLightShow(int dataPin, int lightCount)
{
	_lightCount = lightCount;
	_dataPin = dataPin;
	pinMode(_dataPin, OUTPUT);
}

void GeLightShow::Initialize()
{
	LightData data = {0, 0, 0 , 0};
	SetAllLights(data);
}

void GeLightShow::SetLight(uint8_t address, LightData color)
{
	noInterrupts();
	SendStart();
	for (int i = 0; i < 6; i++)
	{
		if (address & (1 << (5 - i)) > 0)
		{
			SendOne();
		}
		else
		{
			SendZero();
		}
	}
	
	for (int i = 0; i < 20; i++)
	{
		if (address & (1 << (20 - i)) > 0)
		{
			SendOne();
		}
		else
		{
			SendZero();
		}
	}
	
	delayMicroseconds(30);
	interrupts();
}

void GeLightShow::SetAllLights(LightData color)
{
	for (int i = 0; i < _lightCount; i++)
	{
		SetLight(i, color);
	}
}

void GeLightShow::SendStart(void)
{
	digitalWrite(_dataPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(_dataPin, LOW);
}

void GeLightShow::SendZero(void)
{
	digitalWrite(_dataPin, LOW);
	delayMicroseconds(10);
	digitalWrite(_dataPin, HIGH);
	delayMicroseconds(20);
	
	digitalWrite(_dataPin, LOW);
}

void GeLightShow::SendOne(void)
{
	digitalWrite(_dataPin, LOW);
	delayMicroseconds(20);
	digitalWrite(_dataPin, HIGH);
	delayMicroseconds(10);
	
	digitalWrite(_dataPin, LOW);
}